#include "Protocol.hpp"
#include "Sock.hpp"
#include <pthread.h>

void Usage(char *proc)
{
    cout << "Usage:" << proc << " port " << endl;
    exit(1);
}

void *HandlerRequest(void *args)
{
    int sock = *(int *)args;
    pthread_detach(pthread_self());
    // 业务逻辑
    // 1. 获取请求
    request_t req;
    char buffer[1024];
    ssize_t s = read(sock, buffer, sizeof(buffer));
    if (s < 0)
    {
        exit(2);
    }
    // 反序列化请求
    DeserializeRequest(buffer, req);
    cout << "request:" << req.x << req.op << req.y << endl;
    // 2.构建响应
    responce_t resp;
    switch (req.op)
    {
    case '+':
        resp.result = req.x + req.y;
        break;
    case '-':
        resp.result = req.x - req.y;
        break;
    case '*':
        resp.result = req.x + req.y;
        break;
    case '/':
        if (req.y == 0)
            resp.code = -1;
        else
            resp.result = req.x / req.y;
        break;
    case '%':
        if (req.y == 0)
            resp.code = -2;
        else
            resp.result = req.x % req.y;
        break;
    default:
        resp.code = -3;
        break;
    }
    // 3.返回响应结果
    // 序列化响应结果
    string send_string = SerializeResponce(resp);
    write(sock, send_string.c_str(), send_string.size());
    cout << "服务完毕！" << endl;
    close(sock);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
        Usage(argv[0]);
    uint16_t port = atoi(argv[1]);
    int listen_sock = Sock::Socket();
    Sock::Bind(listen_sock, port);
    Sock::Listen(listen_sock);

    for (;;)
    {
        int sock = Sock::Accept(listen_sock);
        if (sock >= 0)
        {
            cout << "get a new client...." << endl;
            pthread_t tid;
            pthread_create(&tid, nullptr, HandlerRequest, &sock);
        }
    }
}